<template>
    <div class="main_content">
        <div class="left">
            <div class="top">
                <Input search @on-search="search" v-model="keyword"  placeholder="请输入姓名、手机号" style="width:280px;" clearable/>
                    <input type="password" autocomplete="new-password" style="display: none" />
            </div>
            <div class="bottom"  v-infinite-scroll="load" infinite-scroll-immediate="isImmediate">
                <ul>
                    <li v-for="(item,index) in list" :key="index" :class="item.id == userId?'active':''" @click="getDetails(item,index)">
                        <span>{{item.nickname}}</span>
                        <p>{{item.phone}}</p>
                    </li>
                </ul>
            </div>
            <div class="num">{{total}}/{{totalCount}}</div>
        </div>
        <div class="right">
            <p>组织角色</p>
            <div class="user">
                <div class="user_left">
                    <div class="list">
                        <div class="item">
                            <span>姓名:</span>
                            <span>{{details.nickname}}</span>
                        </div>
                        <div class="item" v-if="auth.isEditUser">
                            <i class="el-icon-edit-outline" style="color:#1891ff;font-size:16px;cursor: pointer;" @click="update(details)"></i>
                        </div>
                        <!-- <div class="item" v-if="!auth.isEditUser">
                                <i class="el-icon-edit-outline"  style="cursor: not-allowed"></i>
                        </div> -->
                    </div>
                    <div class="list">
                        <div class="item">
                            <span>用户名:</span>
                            <span>{{details.username}}</span>
                        </div>
                        <div class="item">
                            <span>手机号:</span>
                            <span>{{details.phone}}</span>
                        </div>
                    </div>
                </div>
                <div class="user_right">
                    <el-switch  v-model="details.status" active-color="#13ce66" inactive-color="#999" @change="updateStatus(details.status,index,list,false)" v-if="auth.isEnable" v-preventReClick="1500"></el-switch>
                    <el-button  size="small" plain type="primary" @click="add(index,list)" style="margin:0 20px;" v-if="auth.isAddOrgan">添加组织</el-button>
                    <el-button  size="small" plain type="primary" @click="resetpsw(index,list)" style="margin:0 20px;" v-if="auth.isReset">重置密码</el-button>
                    <el-button  size="small" plain :type="!auth.isDelUser  ?'info':'danger'" @click="remove(details)" v-if="auth.isDelUser" >删除账号</el-button>
                </div>
            </div>
            <div class="roleList">
                <ul>
                    <li v-for="(item,index) in roleUserList" :key="index">
                        <div class="role_top">
                            <span>{{item.deptName}}</span>
                            <p>
                                <el-button @click.native.prevent="updateRole(item, index)"  type="text" size="small" v-if="auth.isEditRole">编辑</el-button>
                                <el-button @click.native.prevent="removeRole(item, index)"  type="text" size="small" style="color:red" v-if="auth.isDelRole">删除</el-button>
                            </p>
                        </div>
                        <div class="role_bottom">
                            <span v-for="(value,i) in item.roleList" :key="i">{{value.name}}</span>
                        </div>
                    </li>
                </ul>
            </div>
        </div>

        <Modal v-model="pswModal" title="重置密码" width="520px;" :mask-closable="false">
            <div class="item2">
                <span class="tip">*</span>
                <span>密码:</span>
                <Input v-model="psw" placeholder="请输入密码" style="width: 300px" type="password" clearable/>
            </div>
            <div class="item2">
                <span class="tip">*</span>
                <span>确认密码:</span>
                <Input v-model="pswagain" placeholder="请确认密码" style="width: 300px" type="password" clearable/>
            </div>
            <div slot="footer">
                <el-button @click="cancel(0)" type="info" size="small" plain>取消</el-button>
                <el-button @click="reset(false)" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <Modal v-model="deleteModal" title="删除" width="360px;" :mask-closable="false">
            <div style="margin:10px">确定要删除这条数据吗？</div>
            <div slot="footer">
                <el-button @click="cancel(1)" type="info" size="small" plain>取消</el-button>
                <el-button @click="detele" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <Modal v-model="userModal"  :mask-closable="false" title="编辑账号">
            <div class="top">
                <div class="item2">
                    <span class="tip">*</span>
                    <span>用户名:</span>
                    <Input v-model="username" placeholder="请输入账号编号" style="width: 300px" clearable/>
                </div>
                <div class="item2">
                    <span class="tip">*</span>
                    <span>姓名:</span>
                    <Input v-model="nickname" placeholder="请输入姓名" style="width: 300px" clearable/>
                </div>
                <div class="item2">
                    <span class="tip">*</span>
                    <span>手机号:</span>
                    <Input v-model="phone	" placeholder="请输入手机号" style="width: 300px" clearable/>
                </div>
                <div class="item2">
                    <span>邮箱:</span>
                    <Input v-model="email" placeholder="请输入邮箱" style="width: 300px" clearable/>
                </div>
                <div class="item2">
                    <span class="tip">*</span>
                    <span>账号类型:</span>
                    <div style="width: 300px">
                        <el-radio v-model="type" label="2">普通账号</el-radio>
                        <el-radio v-model="type" label="3">体验账号</el-radio>
                    </div>
                </div>
                <div class="item2" v-if="typeFlag" >
                    <span class="tip">*</span>
                    <span>有效期限:</span>
                    <div style="width: 300px">
                        <DatePicker type="date" placeholder="请选择有限期限" style="width: 200px" v-model="expireTime" :options="options" @on-change="getTime" :transfer="true"></DatePicker>
                        <span v-if="textFlag" style="color:red">已过期</span>
                    </div>
                </div>
            </div>
            <div slot="footer">
                <el-button @click="cancel(5)" type="info" size="small" plain>取消</el-button>
                <el-button @click="addUser" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <Modal v-model="deleteRoleModal" title="删除" width="360px;" :mask-closable="false">
            <div style="margin:10px">确定要删除这条数据吗？</div>
            <div slot="footer">
                <el-button @click="cancel(3)" type="info" size="small" plain>取消</el-button>
                <el-button @click="deteleRole" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <Modal v-model="RoleModal" title="账号角色" width="900px;" :mask-closable="false">
            <div class="role">
                <CheckboxGroup v-model="roleIds" >
                    <Checkbox v-for="(val,index) in roleList" :key="index" :label="val.id" style="width:220px">
                        <span>{{val.name}}</span>
                    </Checkbox>
                </CheckboxGroup>
            </div>
            <div slot="footer">
                <el-button @click="cancel(2)" type="info" size="small" plain>取消</el-button>
                <el-button @click="sumbitRole" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>

        <Modal v-model="addModal" title="添加组织" width="900px;" :mask-closable="false">
            <div style="width:96%;margin:0 auto;margin-bottom:20px" >
                <treeselect
                :multiple="true"
                :options="treeList"
                :flat="true"
                :default-expand-level="1"
                placeholder="请选择组织机构"
                v-model="value"
                :normalizer="normalizer"
                />
                <!-- <treeselect-value :value="value" /> -->
            </div>
            <div class="role">
                <p style="margin-bottom:10px">账号角色</p>
                <CheckboxGroup v-model="roleIds" >
                    <Checkbox v-for="(val,index) in roleList" :key="index" :label="val.id" style="width:220px">
                        <span>{{val.name}}</span>
                    </Checkbox>
                </CheckboxGroup>
            </div>
            <div slot="footer">
                <el-button @click="cancel(4)" type="info" size="small" plain>取消</el-button>
                <el-button @click="sumbitDept" type="primary" size="small" plain v-preventReClick="1500">确定</el-button>
            </div>
        </Modal>
    </div>
</template>
<script>
import {
    getUserList,getUserRemove,getUserEdit,
    getDeptUserRemove,getUserRolesEdit,getAlldeptList,getUserDeptAdd
} from "@/api/api.js";
import {initSys} from "@/mixins/sys.js";
import { toTree, trans,treeSort} from "@/sever/config.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
    mixins:[initSys],
    components: { Treeselect },
    data() {
        return {
            value:[],
            keyword:"",
            list:[],
            userId:"",
            details:"",
            index:0,
            roleUserList:[],
            deleteModal:false,
            removeId:'',
            deleteRoleModal:false,
            roleID:'',
            RoleModal:false,
            addModal:false,
            roleIds:[],
            btnList:[],
            treeList:[],
            pages:1,
            pageNum:0,
            totalCount:0,
            total:0,
            isImmediate:false,
            auth:{
                isEditRole:false,
                isDelRole:false,
                isDelUser:false,
                isEditUser:false,
                isAddOrgan:false,
                isEnable:false,
                isReset:false,
            },
            normalizer(node){
                //去掉children=null的属性
                if(node.children==null||node.children=='null'){
                    delete node.children;
                }
            },
        };
    },
    watch:{
        type(vlaue,oldvalue) {
            if(vlaue == 2) {
                this.typeFlag = false;
            } else if (vlaue == 3) {
                this.typeFlag = true;
            }
        },
    },
    methods: {
        initAuth(){
            this.auth.isEditRole = this.btnList.includes('sys/userRole/edit')
            this.auth.isDelRole = this.btnList.includes('sys/userRole/del')
            this.auth.isDelUser = this.btnList.includes('sys/user/del')
            this.auth.isEditUser = this.btnList.includes('sys/user/edit')
            this.auth.isEnable = this.btnList.includes('sys/user/enable')
            this.auth.isReset = this.btnList.includes('sys/user/resetPassword')
            this.auth.isAddOrgan = this.btnList.includes('sys/user/addOrganization')
        },
        load(){
            if(this.list.length<this.totalCount)
                if(this.pageNum < this.pages) {
                    this.pageNum +=1;
                    this.getList("",false);
            }
        },
        //获取组织机构
        getuserList(){
            getAlldeptList().then(res=>{
                if(res.code == 200){
                    let arr = [];
                    if(res.data.list.length == 1 && res.data.list[0].id == 0) {
                        if(res.data.list[0].children && res.data.list[0].children.length > 0 ) {
                            arr = res.data.list[0].children;
                        }  else {
                            arr = res.data.list;
                        }
                    } else {
                        arr = res.data.list;
                    }
                    this.treeList = treeSort(trans(arr));
                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error=>{
                console.log(error)
            })
        },
        //批量添加组织机构
        add(index,rows){
            this.userId = rows[index].id
            this.addModal =true;
            this.getuserList();
            this.value = [];
            this.roleIds = [];
            this.getRoleList("","",false);
        },
        sumbitDept(){
            if(this.value.length == 0) {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请选择组织机构"
                });
                return;
            }
            if(this.roleIds.length == 0) {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请选择账号角色"
                });
                return;
            }
            let params = {
                userId:this.userId,
                deptIds:this.value,
                roleIds:this.roleIds,
            }
            getUserDeptAdd(params).then(res=>{
                if(res.code == 200) {
                    this.$Message.success("操作成功");
                    // this.getList(this.userId,true);
                    this.getUserRoles(this.userId,"");
                    this.addModal = false;
                } else {
                    this.$Message.warning(res.msg);
                }

            }).catch(error=>{
                console.log(error)
            })
        },
        search(){
            this.list = [];
            this.pageNum = 1;
            this.pages = 1;
            this.getList("",false);
        },
        getList(id,blod){
            let params = {
               pageNum:this.pageNum,
               pageSize:20,
               deptId:"",
               keyword:this.keyword
            }
            getUserList(params).then(res=>{
                if(res.code == 200) {
                    if(!blod){
                        let list = res.data.list
                        this.list =[...this.list,...list];
                        this.pages = res.data.pages;
                        this.totalCount = res.data.total;
                        this.total = this.pageNum * 20;
                        if(this.total >  this.totalCount) {
                            this.total = this.totalCount;
                        }
                    }  else {
                        this.list = res.data.list
                    }
                    if(this.list.length>0) {
                        this.list.forEach(i=>{
                            if(i.status == 0) {
                                i.status =false;
                            } else {
                                i.status = true;
                            }
                        })
                        for(let i = 0; i< this.list.length; i++) {
                            if( id !== "" ){
                                if( id == this.list[i].id){
                                    this.details = this.list[i];
                                    break;
                                } else {
                                    this.details = this.list[0];
                                }
                            } else {
                                this.details = this.list[0];
                            }
                        }
                        this.index = 0;
                        if(id == "") {
                            this.userId = this.list[0].id;
                        } else {
                            this.userId = id;
                        }
                        this.getUserRoles( this.userId,"");
                    }
                } else {
                   this.$Message.warning(res.msg);
               }
           }).catch(error=>{
               console.log(error)
           })
        },
        getDetails(item,index){
            this.userId = item.id;
            this.details = item ;
            this.index = index;
            this.getUserRoles(this.userId,"");
        },
        remove(item){
            this.removeId = item.id;
            this.deleteModal = true;
        },
        detele() {
            getUserRemove(this.removeId)
                .then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.getList("",false);
                        this.deleteModal = false;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        update(item){
            this.getUserDetails(item.id);
            this.userModal = true;
        },
        addUser(){
            var reg = new RegExp( "^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$");
            if (this.username === "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "用户名不能为空"
                });
                return;
            }
            if (this.nickname === "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "姓名不能为空"
                });
                return;
            }
            if (this.phone == "") {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "手机号不能为空"
                });
                return;
            }
            if (this.phone != "") {
                if (!(/^1[3456789]\d{9}$/.test(this.phone) || /^[0-9]{8}$/.test(this.phone))) {
                    this.$Modal.warning({
                        title: "您有必填字段",
                        content: "请填写正确的手机号"
                    });
                    return;
                }
            }
            if (this.email == undefined) {
                this.email = "";
            }
            if (this.email != "") {
                if (!reg.test(this.email)) {
                    this.$Modal.warning({
                        title: "您有必填字段",
                        content: "请填写正确的邮箱号码"
                    });
                    return;
                }
            }
            if(this.type == 3) {
                if(this.expireTime == "") {
                    this.$Modal.warning({
                        title: "您有必填字段",
                        content: "请选择到期时间"
                    });
                    return;
                }
            }
            let params = {
                userId:this.userId,
                username:this.username,
                nickname:this.nickname,
                phone :this.phone,
                email:this.email,
                type:Number(this.type),
                expireTime: this.type== 2 ? '':this.expireTime,
            }
            getUserEdit(params).then(res=>{
                if(res.code == 200) {
                    this.userModal = false;
                    this.getList(this.userId,true);
                    this.$Message.success("操作成功");

                } else {
                    this.$Message.warning(res.msg);
                }
            }).catch(error=>{
                console.log(error);
            })
        },
        updateRole(item,index){
            this.roleIds = [];
            this.roleID = item.deptId;
            this.RoleModal = true;
            this.getRoleList("","",false)
            item.roleList.forEach(i=>{
                this.roleIds.push(i.id)
            })
        },
        sumbitRole(){
            if(this.roleIds.length == 0) {
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "请选择账号角色"
                });
                return;
            }
            let params = {
                deptId:this.roleID,
                userId:this.userId,
                roleIds:this.roleIds,
            }
            getUserRolesEdit(params)
                .then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.getUserRoles( this.userId,"");
                        this.RoleModal = false;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });

        },
        removeRole(item,index){
            this.deleteRoleModal = true;
            this.roleID = item.deptId;

        },
        deteleRole(){
            let params = {
                deptId:this.roleID,
                userId:this.userId,
            }
            getDeptUserRemove(params)
                .then(res => {
                    if (res.code == 200) {
                        this.$Message.success("操作成功");
                        this.keyword = "";
                        this.getUserRoles(this.userId,"");
                        // this.getList("",false);
                        this.deleteRoleModal = false;
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        cancel(type) {
            if(type == 0) {
                this.pswModal = false;
            } else if (type == 1) {
                this.deleteModal = false;
            } else if(type == 3) {
                this.deleteRoleModal = false;
            } else if (type == 2) {
                this.RoleModal = false;
            } else if (type ==  5) {
                this.userModal = false;
            } else if (type == 4) {
                this.addModal =false;
            }
        }
    },
    mounted() {
        this.btnList = JSON.parse(localStorage.getItem("arr"));
        this.initAuth() //初始化权限
        this.pageNum = 1
        this.getList("",false);
    },
};
</script>
<style lang="less" scoped>
@import "./../../assets/style/themeBase.less";
.main_content {
    width: 100%;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
    background: #f5f5f5;
    display: flex;
    .left {
        width: 300px;
        height: 100%;
        margin-right: 10px;
        background: #fff;
        border-radius: 10px;
        padding: 10px;
        .num{
            width: 100%;
            height: 30px;
            text-align: center;
            line-height: 30px;
            color:#1891ff;
            font-size: 16px;
        }
        .top {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            width: 280px;
            height: 50px;
        }
        .bottom {
            width: 280px;
            height: calc(100% - 80px);
            overflow-y: scroll;
            border:1px solid #f5f5f5;
            ul {
                width: 100%;
                display: flex;
                flex-direction: column;
                li {
                    height: 50px;
                    white-space: nowrap;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    padding: 0 10px;
                    width: 270px;
                    border-bottom: 1px solid #f2f2f2;
                    cursor: pointer;
                    span {
                        width: 200px;
                    }
                    p {
                        width: 200px;
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                    }
                }
                .active {
                    background: var(--themeColor);
                    color: #fff;
                }
            }
        }
        .bottom::-webkit-scrollbar {
            width: 6px;
        }
        /*滚动槽*/
        .bottom::-webkit-scrollbar-track {
            -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
            box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
            border-radius: 10px;
        }
        /* 滚动条滑块 */
        .bottom::-webkit-scrollbar-thumb {
            border-radius: 10px;
            background: rgba(0, 0, 0, 0.1);
            -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5);
            box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.5);
        }
        .bottom::-webkit-scrollbar-thumb:window-inactive {
            background: rgba(255, 0, 0, 0.4);
        }
    }
    .right {
        flex: 1;
        height: 100%;
        overflow: hidden;
        background: #fff;
        border-radius: 10px;
        padding: 20px;
        p{
            color: var(--themeColor);
            height: 30px;
            width: 100%;
            border-bottom: 1px solid #f2f2f2;
            font-size: 16px;
        }
        .user{
            background: #f2f2f2;
            height: 60px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding:10px;
            .user_left{
                // padding:5px;
                .list{
                    margin-top:5px;
                    .item{
                        margin-right: 20px;
                    }
                }
            }
        }
        .roleList{
            margin-top: 20px;
            height: calc(100% - 100px);
            overflow-y: scroll;
            ul{
                width: 100%;
                height: 100%;
                list-style: none;
                li{
                    width: 100%;
                    height: auto;
                    display: flex;
                    flex-direction: column;
                    justify-content: flex-start;
                    margin-bottom: 10px;
                    .role_top{
                        width: 100%;
                        height: 30px;
                        display: flex;
                        justify-content: space-between;
                        p{
                            border: none;
                            width: 80px;
                        }
                        span{
                            color: #000;
                            font-size: 18px;
                        }
                    }
                    .role_bottom{
                        display: flex;
                        flex-wrap: wrap;
                        justify-content: flex-start;
                        span{
                            width: 250px;
                            font-size: 14px;
                            // color: #f2f2f2;
                            margin-bottom: 5px;
                        }
                    }
                }
            }
        }
        .roleList::-webkit-scrollbar {
            display: none;
        }
        /*兼容火狐*/
        .roleList {
            scrollbar-width: none;
        }
        .roleList {
            -ms-overflow-style: none;
        }
    }
}
.tip {
    width:10px !important;
    color: red;
    font-size: 16px;
}
.list {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 10px;

    span {
        width: 70px;
    }
}
.item2 {
    width: 80%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    height: 32px;
    position: relative;
    span {
        width: 120px;
        margin-left: 10px;
    }
    .tip {
        position: absolute;
        color: red;
        font-size: 16px;
        left: -10px;
        top: 5px;
        width: 5px;
    }
}
.role{
    width: 96%;
    margin:0 auto;
    padding:10px;
    border-radius: 10px;
    border:1px solid #f2f2f2;
}
</style>
